package com.bnz.servlet;

import com.alibaba.fastjson.JSON;
import com.bnz.pojo.PageResult;
import com.bnz.pojo.R;
import com.bnz.pojo.Student;
import com.bnz.service.StudentService;
import com.bnz.service.impl.StudentServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/student")
public class StudentServlet extends HttpServlet {

    private StudentService studentService;

    @Override
    public void init() throws ServletException {
        //1. 在servlet中得到spring容器
        WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        //2. 得到studentService
        studentService = wac.getBean(StudentService.class);
    }

    //1. 根据请求参数调用方法
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.1 得到请求参数
        String cmd = req.getParameter("cmd");
        //1.2 根据参数调用方法
        if (StringUtils.isNotBlank(cmd)){
            if ("list".equals(cmd)){            //列表学生
                list(req,resp);
            }
            if ("findByPage".equals(cmd)){      //分页查询
                findByPage(req,resp);
            }
        }
    }



    //2. 列表学生
    private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //2.1 查询所有学生
        List<Student> students = studentService.findAll();
        //2.2 将学生转换为json
        resp.getWriter().println(JSON.toJSONString(R.ok().data("data",students)));
        //2.3 刷新页面
        resp.getWriter().flush();

    }

    //3. 分页查询
    private void findByPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //3.1 得到当前页与每页大小
        int page = new Integer(req.getParameter("page"));
        int pageSize = new Integer(req.getParameter("pageSize"));
        //3.2 开始分页查询
        PageResult pr = studentService.findByPage(page,pageSize);
        //3.3 提交分页数据到前台
        resp.getWriter().println(JSON.toJSONString(R.ok().data("pr",pr)));
        //3.4 刷新页面
        resp.getWriter().flush();
    }
}
